package com.tandan.mqttdemo0730.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tandan.mqttdemo0730.config.MqttConfig;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * MQTT发布服务
 */
@Service
public class MqttService {

    private static final Logger logger = LoggerFactory.getLogger(MqttService.class);

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private MqttConnectOptions mqttConnectOptions;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${mqtt.topic}")
    private String topic;

    @Value("${mqtt.qos:1}")
    private int qos;

    @Value("${mqtt.retained:false}")
    private boolean retained;

    private MqttClient mqttClient;
    private final Random random = new Random();

    /**
     * 初始化MQTT客户端连接
     */
    @PostConstruct
    public void init() {
        try {
            mqttClient = new MqttClient(mqttConfig.getBrokerUrl(), mqttConfig.getClientId());
            
            // 设置回调
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    logger.warn("MQTT连接丢失: {}", cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // 这里可以处理接收到的消息
                    logger.info("收到消息 - Topic: {}, Message: {}", topic, new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    logger.debug("消息发送完成: {}", token.getMessageId());
                }
            });

            // 连接到MQTT代理
            connect();
            
        } catch (MqttException e) {
            logger.error("MQTT客户端初始化失败", e);
        }
    }

    /**
     * 连接到MQTT代理
     */
    private void connect() {
        try {
            if (!mqttClient.isConnected()) {
                mqttClient.connect(mqttConnectOptions);
                logger.info("MQTT客户端连接成功: {}", mqttConfig.getBrokerUrl());
            }
        } catch (MqttException e) {
            logger.error("MQTT连接失败", e);
        }
    }

    /**
     * 发布消息到MQTT
     *
     * @param topic   主题
     * @param payload 消息内容
     */
    public void publish(String topic, String payload) {
        try {
            if (!mqttClient.isConnected()) {
                connect();
            }

            MqttMessage message = new MqttMessage(payload.getBytes());
            message.setQos(qos);
            message.setRetained(retained);

            mqttClient.publish(topic, message);
            logger.info("消息发布成功 - Topic: {}, Payload: {}", topic, payload);

        } catch (MqttException e) {
            logger.error("消息发布失败 - Topic: {}, Payload: {}", topic, payload, e);
        }
    }

    /**
     * 发布消息到默认主题
     *
     * @param payload 消息内容
     */
    public void publish(String payload) {
        publish(topic, payload);
    }

    /**
     * 发布对象消息（自动转换为JSON）
     *
     * @param topic  主题
     * @param object 要发布的对象
     */
    public void publishObject(String topic, Object object) {
        try {
            String json = objectMapper.writeValueAsString(object);
            publish(topic, json);
        } catch (JsonProcessingException e) {
            logger.error("对象序列化为JSON失败", e);
        }
    }

    /**
     * 发布对象消息到默认主题
     *
     * @param object 要发布的对象
     */
    public void publishObject(Object object) {
        publishObject(topic, object);
    }

    /**
     * 生成模拟数据并发布
     */
    public void publishSimulatedData() {
        Map<String, Object> data = new HashMap<>();
        data.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        data.put("temperature", 20 + random.nextDouble() * 15); // 20-35度
        data.put("humidity", 40 + random.nextDouble() * 40);    // 40-80%
        data.put("pressure", 1000 + random.nextDouble() * 50);  // 1000-1050 hPa
        data.put("deviceId", "sensor" + MqttService.getNumber());
        data.put("location", "机房A区");

        publishObject(data);
    }

    public static String getNumber() {
        SecureRandom secureRandom = new SecureRandom();
        int randomNumber = secureRandom.nextInt(10000); // 0-9999
        String formattedNumber = String.format("%04d", randomNumber); // 格式化为4位
        return formattedNumber;
    }


    /**
     * 断开连接
     */
    @PreDestroy
    public void disconnect() {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.disconnect();
                mqttClient.close();
                logger.info("MQTT客户端连接已断开");
            }
        } catch (MqttException e) {
            logger.error("MQTT断开连接失败", e);
        }
    }

    /**
     * 检查连接状态
     */
    public boolean isConnected() {
        return mqttClient != null && mqttClient.isConnected();
    }
}